package com.lunhui.search.dal.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author renminghe-kg
 */
public class ESBaseServiceImpl {

    @Resource(name = "restLowLevelClient")
    private RestClient restLowLevelClient;

    public JSONObject getEs(JSONObject queryParam, String url) throws IOException {
        HttpEntity entity = new NStringEntity(queryParam.toJSONString(), ContentType.APPLICATION_JSON);
        Request request = new Request("POST", url);
        request.setEntity(entity);
        Response lowResponse = restLowLevelClient.performRequest(request);
        String responseBody = EntityUtils.toString(lowResponse.getEntity());
        return JSON.parseObject(responseBody);
    }

    public JSONObject addEs(String userStr, String url) throws IOException {
        HttpEntity entity = new NStringEntity(userStr, ContentType.APPLICATION_JSON);
        Request request = new Request("POST", url);
        request.setEntity(entity);
        Response lowResponse = restLowLevelClient.performRequest(request);
        String responseBody = EntityUtils.toString(lowResponse.getEntity());
        return JSON.parseObject(responseBody);
    }
}